package cn.alterzhang.www.test;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * Created by zhangshuhan on 2019/1/30.
 */
public class ZK implements Watcher {

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws Exception {
        String path = "/zk-book";
        zooKeeper = new ZooKeeper("198.181.39.68:2181", 5000, new ZK());
        System.out.println(zooKeeper.getState() + "======SessionId:" + zooKeeper.getSessionId() + "=======SessionPasswd:" + zooKeeper.getSessionPasswd());

        countDownLatch.await();

        System.out.println(zooKeeper.getState() + "===SessionId:" + zooKeeper.getSessionId() + "=====SessionPasswd:" + zooKeeper.getSessionPasswd());

        zooKeeper.exists(path, true);

        zooKeeper.create(path, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        zooKeeper.setData(path, "zookeeper实战".getBytes(), -1);

        zooKeeper.create(path + "/c1", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        zooKeeper.delete(path + "/c1", -1);

        zooKeeper.delete(path, -1);

        Thread.sleep(Integer.MAX_VALUE);

    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("watchedEvent start");
        try {
            if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {

                if (Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()) {
                    countDownLatch.countDown();
                } else if (Event.EventType.NodeCreated == watchedEvent.getType()) {
                    System.out.println("nodeCreated:" + watchedEvent.getPath());
                    zooKeeper.exists(watchedEvent.getPath(), true);
                }else if (Event.EventType.NodeDataChanged==watchedEvent.getType()){
                    System.out.println("NodeDataChanged:" + watchedEvent.getPath());
                    zooKeeper.exists(watchedEvent.getPath(), true);
                }else if (Event.EventType.NodeDeleted==watchedEvent.getType()){
                    System.out.println("NodeDeleted:" + watchedEvent.getPath());
                    zooKeeper.exists(watchedEvent.getPath(), true);
                }
            }
        } catch (Exception e) {

        }

    }
}
